import {
  ui
} from '../../../../tools/ui';
import {
  ds
} from '../../../../tools/data'
import {
  dsx
} from '../../../../tools/datax'
import {
  users
} from '../../../../tools/users'
import {
  dateTool
} from '../../../../tools/date'
import {
  checkTool
} from '../../../../tools/check';
import {
  numTool
} from '~/tools/num'

Page({
  data: {
    staff: {},
    pickerIndexList: [0, 0, 0], //日期选择器下标
    isShowDateLayer: false, //是否显示日期弹层
    txtDate: '请选择日期', //选中日期
    isSeltDate: false, //是否选择日期
    date: {},
    loading: true,
    readOnly: true,
    unitFee: 3.5,
    orders: []
  },
  onLoad(options) {
    const {
      nickName,
      staffId
    } = options
    const title = nickName + '的配送费'
    wx.setNavigationBarTitle({
      title
    })
    this.setData({
      title
    })
    this.init(staffId)

    // that.getCurrentDate(); // 获取当前时间
    // that.setData({
    //   pickerIndexList: that.data.pickerIndexList
    // })

  },
  async init(staffId) {
    ui.loading()
    await this.loadSetting()
    const staff = await this.loadStaff(staffId)
    const history = await this.setDateRange(staff.deliveryFee || [])
    await this.calcFee(history.start, history.end)
    this.loadUser()
    ui.loading(false)
  },
  async loadSetting() {
    await ds.coll('setting')
      .where({
        _id: ds.cmd.exists(true)
      })
      .field({
        deliveryFee: true
      })
      .get()
      .then(res => {
        const unitFee = res.data[0].deliveryFee
        this.setData({
          unitFee
        })
        this.settingId = res.data[0]._id
      })
  },
  async loadStaff(staffId) {
    const res = await ds.coll('users')
      .where({
        _id: staffId
      })
      .get()
    const staff = res.data[0]
    // console.log(staff)
    staff.deliveryFee?.sort((a, b) => {
      return b.start - a.start
    })
    this.setData({
      staff
    })
    return staff
  },
  loadUser() {
    users.getUserInfo()
      .then(u => {
        this.setData({
          readOnly: u.role != 'admin'
        })
      })
  },
  async setDateRange() {
    const {
      staff
    } = this.data

    const now = new Date()
    let start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(),
      end = now.getTime()
    const _ = ds.cmd
    const res = await ds.coll('orders').where({
      deliveryMan: staff._openid,
      status: '已送达',
      deliveryFeePaid: _.exists(false).or(_.eq(false))
    }).orderBy('createTime', 'asc').limit(1).get()

    // console.log(res)
    if (res.data.length > 0) {
      start = res.data[0].createTime
    }

    this.setData({
      date: {
        start,
        end
      }
    })
    return {
      start,
      end
    }
  },
  async calcFee(start, end) {
    // console.log(start, end)
    const {
      staff,
      unitFee,
    } = this.data

    // 该员工配送的订单
    const _ = ds.cmd
    const orders = await ds.getAll('orders', {
      deliveryMan: staff._openid,
      status: '已送达',
      deliveryFeePaid: _.exists(false).or(_.eq(false)),
      createTime: _.and(start ? _.gte(start) : {}, _.lte(end))
    })
    if (!orders) return

    // 计算费用
    let bucketNumMap = {} // { fee: num, total: totalNum }
    let bucketNum = 0,
      totalBucketFee = 0,
      totalStepFee = 0
    orders.forEach(order => {
      const findSnap = function (id) {
        return order.goodsSnap.find(ele => ele._id == id)
      }
      order.goodsList.forEach((goods) => {
        const useFee = findSnap(goods.spuId)?.deliveryFee || unitFee
        const bucketFee = goods.num * useFee
        totalBucketFee += bucketFee

        bucketNumMap[useFee.toFixed(2)] = (bucketNumMap[useFee.toFixed(2)] ?? 0) + goods.num
        bucketNum += goods.num
      })
      totalStepFee += (Number(order.stepFee) || 0)
    })
    // const totalFee = bucketNum * unitFee + totalStepFee
    const totalFee = totalBucketFee + totalStepFee
    const bucketNumList = []
    Object.keys(bucketNumMap).forEach(useFee => {
      bucketNumList.push({
        unit: numTool.maxFixed(useFee, 2),
        num: bucketNumMap[useFee]
      })
    })
    // console.log(bucketNumList)
    this.setData({
      fee: numTool.maxFixed(totalFee, 2),
      stepFee: totalStepFee,
      num: bucketNum,
      numList: bucketNumList,
      orders
    })
  },
  setTap() {
    if (this.data.readOnly) return
    const {
      unitFee
    } = this.data
    const that = this
    ui.text('设置配送费（元/桶）', unitFee + "(商品未单独设置时有效)", (ok, text) => {
      if (!ok) return
      checkTool.check([{
        title: '输入',
        value: text,
        fn: val => checkTool.test(val, checkTool.CommonRegex.decimal) && Number(val) > 0
      }])
      const newFee = Number(text)
      ui.loading()
      ds.cloudUpdate('setting', that.settingId, {
        deliveryFee: newFee
      }, res => {
        const success = res.result.errMsg.endsWith(':ok')
        ui.toast(success)
        if (success) that.init(that.data.staff._id)
        ui.loading(false)
      })
    })
  },
  async onSettleTap() { // 结算
    const {
      staff,
      orders,
      date,
      fee,
      num,
      stepFee,
      unitFee
    } = this.data
    // console.log(date)

    const doSettle = async () => {
      ui.loading()
      const deliveryFee = (staff.deliveryFee || [])
      const orderIds = [],
        _ = dsx.cmd
      for (const o of orders) {
        orderIds.push(o._id)
      }
      // console.log(orderIds)
      const res = await dsx.cloudUpdateByIds('orders', orderIds, {}, {
        deliveryFeePaid: true
      })
      if (res.result?.stats?.updated != orderIds.length) {
        ui.loading(false)
        ui.toast(false, res.errMsg)
        return
      }
      // console.log(res)
      deliveryFee.push({
        start: date.start,
        end: date.end,
        fee,
        num,
        stepFee,
        unitFee
      })
      // console.log('deliveryFee', deliveryFee, staff._id)

      // 更新
      ds.cloudUpdate('users', staff._id, {
        deliveryFee
      }, res => {
        this.init(this.data.staff._id)
      })
    }

    ui.confirm('确定结算吗？', res => {
      if (!res) return
      doSettle()
    })
  },
  onShow() {},
  initDateRange() {
    const dateRange = this.data.dateRange;
    dateRange.start = this.getStartTime();
    dateRange.end = new Date().getTime()
    this.setData(dateRange)
  },
  updateDateRange() {
    const dpStart = this.selectComponent("#dpstart"),
      dpEnd = this.selectComponent("#dpend");
    dpStart.initTimestamp(this.data.dateRange.start);
    dpEnd.initTimestamp(this.data.dateRange.end)
  },
  async onSttsTap() {
    const {
      start,
      end
    } = this.data.date
    // console.log(new Date(start), new Date(end))
    ui.loading()
    await this.calcFee(start, end)
    ui.loading(false)
  },
  onPickStartDate(e) {
    const {
      timestamp
    } = e.detail;
    // console.log(new Date(timestamp))
    this.setData({
      date: {
        start: timestamp,
        end: this.data.date.end
      }
    })
    // console.log(new Date(timestamp))
    this.justifyDateRange()
  },
  onPickEndDate(e) {
    const {
      timestamp
    } = e.detail;
    this.setData({
      date: {
        start: this.data.date.start,
        end: dateTool.dayEnd(timestamp)
      }
    })
    // console.log(new Date(timestamp), new Date(this.data.date.end))
    this.justifyDateRange()
  },
  justifyDateRange() {
    let {
      start,
      end
    } = this.data.date
    if (start > end) {
      end = dateTool.dayEnd(start);
      this.setData({
        date: {
          start,
          end
        }
      })
    }
  },
  onFeeTap() {
    const {
      date,
      staff,
      unitFee
    } = this.data
    this.showFeeOrders(staff._openid, date, unitFee, false)
  },
  feeCellTap(e) {
    const {
      unitFee
    } = this.data
    const item = ui.eventData(e, 'item'),
      staffOpenId = ui.eventData(e, 'staffopenid')
    const {
      start,
      end
    } = item
    // console.log(item)
    this.showFeeOrders(staffOpenId, {
      start,
      end
    }, unitFee, true)
  },
  showFeeOrders(staffOpenId, date, unitFee, paid) {
    const item = {
      start: date.start,
      end: date.end,
      unitFee
    }
    const sitem = JSON.stringify(item)
    wx.navigateTo({
      url: `/pages/usercenter/staff/deliveryFee/list/feeList?unitFee=${unitFee}&item=${sitem}&staffOpenId=${staffOpenId}&paid=${paid}`,
    })
  }
})